import React, { useEffect, useMemo, useState } from "react";
import NavBar from "@/components/NavBar/NavBar";
import SvgIcon from "@/components/SvgIcon/SvgIcon";
import EvaluateItem from "@/components/EvaluateItem/EvaluateItem";
import GoodCard from "@/components/GoodCard/GoodCard";
import BackTop from "@/components/BackTop/BackTop";
import { useNavigate, useSearchParams } from "react-router-dom";
import { useEnhanceDispatch, useEnhanceSelector } from "@/hooks";
import { Button, ImageViewer, Modal, Popup, Stepper, Swiper, Toast } from "antd-mobile";
import { fetchCommentRowsThunk, fetchServiceThunk, findGoodDetailThunk } from "@/store/modules/goodDetailStore";
import { RightOutline } from "antd-mobile-icons";
import type { GoodDetail as DetailType } from "@/type/GoodDetailType";
import type { Comment } from "@/type/GoodDetailType";
import type { AddOrUpdateCartParams } from "@/type/CartType";
import { addCartThunk } from "@/store/modules/cartStore";
import useCartTotal from "@/hooks/useCartTotal";
import { settleAccountsInfoThunk } from "@/store/modules/orderStore";
import { SettleAccountsParams } from "@/type/OrderType";
import "./GoodDetail.scss";

const GoodDetail = () => {
   const navigate = useNavigate();
   const enhanceDispatch = useEnhanceDispatch();
   const token = useEnhanceSelector(state => state.loginStore.loginData).token;
   const serviceList = useEnhanceSelector(state => state.goodDetailStore.serviceList);
   const cartTotal = useCartTotal();
   const [searchParams, setSearchParams] = useSearchParams();
   // 商品ID
   const goodsId: string = searchParams.get("goodsId") as string;
   // 商品详情
   const goodDetail: DetailType = useEnhanceSelector(state => state.goodDetailStore.goodDetail);
   // 评价
   const comment: Comment[] = useEnhanceSelector(state => state.goodDetailStore.comment);
   // 是否显示图片预览
   const [visible, setVisible] = useState(false);
   // 图片数组
   const external_urls: string[] = useMemo(() => goodDetail?.goods_images?.map(item => item.external_url), [goodDetail.goods_images]);
   // 是否显示添加或者购买的弹层组件
   const [visiblePopup, setVisiblePopup] = useState(false);
   // 加入购物车还是立即购买
   const [controls, setControls] = useState<"add" | "pay">();
   // 加入购物车的参数
   const [params, setParams] = useState<AddOrUpdateCartParams>({
      goodsId,
      goodsNum: 1,
      goodsSkuId: "0",
   });
   // 获取订单结算信息的参数
   const [settleAccounts, setSettleAccounts] = useState<SettleAccountsParams>({
      mode: "buyNow",
      delivery: 10,
      couponId: 0,
      isUsePoints: 0,
      goodsSkuId: goodDetail?.skuList?.map(item => item.goods_sku_id).join() || "0",
      goodsNum: 0,
      goodsId,
   });
   const [loading, setLoading] = useState<boolean>(false);

   /**
    * @description获取商品详情的回调函数
    * */
   const findGoodDetail = async () => {
      try {
         await enhanceDispatch(findGoodDetailThunk(goodsId)).unwrap();
      } catch (rejectedValueOrSerializedError: any) {
         Toast.show(rejectedValueOrSerializedError);
      }
   };

   /**
    * @description 获取详情页面商品评价的回调函数
    * */
   const fetchCommentRows = async () => {
      try {
         await enhanceDispatch(fetchCommentRowsThunk({ goodsId, limit: 5 })).unwrap();
      } catch (rejectedValueOrSerializedError: any) {
         Toast.show(rejectedValueOrSerializedError);
      }
   };

   /**
    * @description 显示弹层组件的回调函数
    * */
   const changeVisiblePopup = (controls: "add" | "pay") => {
      setVisiblePopup(true);
      setControls(controls);
   };

   /**
    * @description 点击mask关闭弹层组件的回调函数
    * */
   const onMaskClick = () => {
      setVisiblePopup(false);
   };

   /**
    * @description 点击加入购物车按钮的回调函数
    * */
   const handleAddCart = async () => {
      if (!token) {
         const result: boolean = await Modal.confirm({ content: "加入购物车需要登录,确认登录吗?" });
         if (result) {
            navigate("/login");
            return;
         } else {
            setVisiblePopup(false);
            return;
         }
      }
      try {
         setLoading(true);
         await enhanceDispatch(addCartThunk(params)).unwrap();
         setVisiblePopup(false);
         Toast.show({ icon: "success", content: "加入购物车成功" });
      } catch (rejectedValueOrSerializedError: any) {
         Toast.show(rejectedValueOrSerializedError);
      } finally {
         setLoading(false);
      }
   };

   /**
    * @description 点击立即购买按钮的回调函数
    * */
   const handlePay = async () => {
      if (!token) {
         const result: boolean = await Modal.confirm({ content: "立即购买需要登录,确认登录吗?" });
         if (result) {
            navigate("/login");
            return;
         } else {
            setVisiblePopup(false);
            return;
         }
      }
      try {
         setLoading(true);
         const newSettleAccounts = { ...settleAccounts, goodsNum: params.goodsNum };
         setSettleAccounts(newSettleAccounts);
         await enhanceDispatch(settleAccountsInfoThunk(newSettleAccounts));
         navigate(`/checkout?mode=${settleAccounts.mode}&goodsId=${settleAccounts.goodsId}&goodsSkuId=${settleAccounts.goodsSkuId}&goodsNum=${params.goodsNum}&delivery=${settleAccounts.delivery}&couponId=${settleAccounts.couponId}&isUsePoints=${settleAccounts.isUsePoints}`);
         Toast.show({ icon: "success", content: "订单结算成功" });
      } catch (rejectedValueOrSerializedError: any) {
         Toast.show(rejectedValueOrSerializedError);
      } finally {
         setLoading(false);
      }
   };

   const changeGoodsNum = (goodsNum: number) => {
      setParams({ ...params, goodsNum });
   };


   const inventory = useMemo(() => {
      if (goodDetail) {
         if (goodDetail.skuList) {
            if (goodDetail.skuList.length) {
               return goodDetail.skuList[0].stock_num;
            }
         }
      }
   }, [goodDetail.skuList]);


   useEffect(() => {
      findGoodDetail();
      fetchCommentRows();
   }, []);

   useEffect(() => {
      enhanceDispatch(fetchServiceThunk(goodsId)).unwrap();
   }, []);
   return (
      <div className="good-detail-container">
         <div className="detail-header">
            <NavBar children="商品详情" backIcon onBack={() => navigate(-1)}></NavBar>
         </div>
         <div className="detail-main">
            <div className="swiper" onClick={() => setVisible(true)}>
               <Swiper loop autoplay>
                  {
                     goodDetail?.goods_images?.map((item, index) => {
                        return (
                           <Swiper.Item key={index}>
                              <img src={item.external_url} alt="" />
                           </Swiper.Item>
                        );
                     })
                  }
               </Swiper>
            </div>
            <ImageViewer.Multi images={external_urls} visible={visible} defaultIndex={0} onClose={() => setVisible(false)}></ImageViewer.Multi>
            <div className="info">
               <div className="top">
                  <div className="price-box">
                     <span className="price">￥{goodDetail?.goods_price_max}</span> <span className="old-price">￥{goodDetail?.line_price_max}</span>
                  </div>
                  <div className="sales">
                     <span>已售出{goodDetail?.goods_sales}件</span>
                  </div>
               </div>
               <div className="bottom ellipsis-multi">{goodDetail?.goods_name}</div>
            </div>
            <div className="service">
               <div className="message">
                  {
                     serviceList.map(item => {
                        return (
                           <span key={item.service_id}>
                             <SvgIcon name="success" width="15px" height="15px"></SvgIcon>
                              <i>{item.name}</i>
                           </span>
                        );
                     })
                  }
               </div>
               <div className="more">
                  <span>查看更多</span>
                  <RightOutline />
               </div>
            </div>
            <div className="evaluate">
               <div className="evaluate-header">
                  <div className="count">商品评价(10)</div>
                  <div className="more" onClick={() => navigate(`/comment-list?goodsId=${goodsId}`)}>
                     <span>查看更多</span>
                     <RightOutline />
                  </div>
               </div>
               <div className="evaluate-list">
                  {
                     comment?.map((item, index) => {
                        return (<EvaluateItem comment={item} key={index}></EvaluateItem>);
                     })
                  }
               </div>
            </div>
            <div className="img-message">
               <div className="message-header">商品描述</div>
               <div className="content" dangerouslySetInnerHTML={{ __html: goodDetail?.content }}></div>
            </div>
         </div>
         <div className="cart-bar">
            <div className="icon" onClick={() => navigate("/")}>
               <SvgIcon name="home-default" width="20px" height="20px"></SvgIcon>
               <span>首页</span>
            </div>
            <div className="icon" onClick={() => navigate("/cart")}>
               <SvgIcon name="cart-default" width="20px" height="20px"></SvgIcon>
               <span>购物车</span>
            </div>
            <Button color="primary" className="cart" onClick={() => changeVisiblePopup("add")}>加入购物车</Button>
            <Button color="primary" className="pay" onClick={() => changeVisiblePopup("pay")}>立即购买</Button>
         </div>
         <Popup showCloseButton onMaskClick={onMaskClick} visible={visiblePopup} bodyStyle={{ borderTopLeftRadius: "20px", borderTopRightRadius: "20px" }}>
            <GoodCard good={goodDetail} inventory={inventory} isShowInventory></GoodCard>
            <div className="count">
               <span>数量</span>
               <Stepper min={1} value={params.goodsNum} onChange={changeGoodsNum}></Stepper>
            </div>
            <div className="controls">
               {controls === "add" ? <Button className="add" onClick={handleAddCart} loading={loading} disabled={inventory === 0}>{inventory === 0 ? "该商品没库存" : "加入购物车"}</Button> : <Button block className="pay" onClick={handlePay} loading={loading} disabled={inventory === 0}>{inventory === 0 ? "该商品没库存" : "立即购买"}</Button>}
            </div>
         </Popup>
         <BackTop></BackTop>
      </div>
   );
};

export default GoodDetail;
